import datetime
import time
import os
from collections import OrderedDict
from django.db.models import Q
from rest_framework.decorators import throttle_classes
from django_filters.rest_framework import DjangoFilterBackend
from django.shortcuts import redirect
from rest_framework import filters
from rest_framework import mixins, viewsets, status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.views import JSONWebTokenAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.settings import api_settings
from finance_c2c.local_settings import Config
from finance_c2c.settings import MEDIA_ROOT

from core.tools.edit_photo import EditPicture
from .serializers import VisitListSerializer, NoCodeSerializer, TelCodeSerializer, \
    VerClickProductSerializer, BaseClickProductSerializer, ClickProductSerializer, SalesManSerializer, \
    MyLoginSerializer, MyInfoSerializer, UserModel, TeamSerializers, TeamDetailsSerializers, BandLeaderSerializers, \
    BankCardNoSerializers, TelSerializers, BaseBankCardNoSerializers, UfSerializers, NameSerializers, LeaderSerializers, \
    MenusSerializers, WXLoginSerializer, NickNameSerializers, PopularSerializers
from .admin_serializers import AdminLoginSerializers
from apps.user_operation.permissions import IsOwner
from apps.sales_man.models import SalesMan, Single
from apps.product.models import Product
from apps.supply_order.models import BasePopularImg, PopularQrCode
from apps.utils.views import apply
from core.tools.models import PublicPrivate
from core.tools.encryption import md5
from core.tools.paginator import DjangoPaginator
from core.tools.throttles import TransferRateThrottle
from core.tl.client import get_TLClient
from apps.supply_order.utils import UntilPagination
from .models import LevelDesc, Menus, UserProfileExtend
from . import filters as my_filters
from apps.czb.client import get_czb_api
from apps.czb.utils import distance_sorted, in_time_update_oil
from apps.czb.utils import get_czb_channel_auth

jwt_response_payload_handler = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER


class RegisterViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    """
    手机号身份证注册接口
        create: 手机号身份证注册接口
    """
    queryset = SalesMan.objects.all()
    serializer_class = SalesManSerializer
    # authentication_classes = (JSONWebTokenAuthentication,)


class ClickProductViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    def get_serializer_class(self):
        """
        Return the serializer instance that should be used for validating and
        deserializing input, and for serializing output.
        """
        try:
            if self.request.method == "POST":
                ver = self.request.POST.get("ver_code")
                product = self.request.POST.get("product")
                product = Product.objects.filter(id=product)
                if product:
                    if product.first().is_firm:
                        return BaseClickProductSerializer
                if ver:
                    return VerClickProductSerializer
                else:
                    return ClickProductSerializer
        except Exception as e:
            print(e)
            return ClickProductSerializer

    def create(self, request, *args, **kwargs):
        data = request.data
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        product_id = data.get("product")
        product_obj = Product.objects.get(id=product_id)
        apply_obj = self.perform_create(serializer)
        if product_obj.sign_type != 4:  # 如果不是主产品
            # 如果没有子产品
            if product_obj.api_type == 2 and product_obj.sign_type == 2:
                # 如果是思兮API
                apply_status, content = apply(product_obj, apply_obj)
                if apply_status:
                    content = {"url": content.get("bank_url"), "status": "ok", "id": product_obj.id}
                else:
                    content = {"status": "error", "msg": content.get("message")}
            else:
                # 不是思兮的
                content = {"url": product_obj.url, "status": "ok"}
            Single.objects.create(
                product=product_obj,
                b_user=apply_obj.salesman,
                t_user=apply_obj.salesman.leader,
                applicant=apply_obj,
            )
            return Response(content, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        return serializer.save()


class TelCodeViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    def get_serializer_class(self):
        """
        Return the serializer instance that should be used for validating and
        deserializing input, and for serializing output.
        """
        try:
            ver = self.request.POST.get("ver_code")
            if ver:
                return TelCodeSerializer
            else:
                return NoCodeSerializer
        except Exception as e:
            print(e)
            return NoCodeSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        return Response(serializer.data, status=status.HTTP_201_CREATED)


class GetVisit(APIView):
    """
    View to list all users in the system.

    * Requires token authentication.
    * Only admin users are able to access this view.
    """
    serializer_class = VisitListSerializer

    def post(self, request, format=None):
        """
        Return a list of all users.
        """
        account = request.POST.get("account")
        password = request.POST.get("password")
        password = md5(md5(password))
        try:
            salesman = SalesMan.objects.get(account=account, password=password)
        except Exception as e:
            print(e)
            return Response({"message": "账号密码错误"})
        child_list = salesman.salesman_set.all()
        child_list, page_dict = DjangoPaginator.get_paging(child_list)
        child_data_list = []
        for i in child_list:
            data = dict()
            data["lower_level"] = i.account
            data["lower_level_team"] = i.num
            child_data_list.append(data)
        return Response({"message": "SUCCESS", "data": {"child_list": child_data_list, "page_dict": page_dict}})


# 注册登录
class LoginRegisterViewSet(JSONWebTokenAPIView):
    serializer_class = MyLoginSerializer


# 团队列表
class TeamViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    pagination_class = UntilPagination
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    permission_classes = (IsAuthenticated, IsOwner)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.TeamFilter
    serializer_class = TeamSerializers

    def get_serializer_class(self):
        if self.action == "retrieve":
            return TeamDetailsSerializers
        else:
            return TeamSerializers

    def get_queryset(self):
        user = self.request.user
        return UserModel.objects.filter(leader=user).order_by('-create_time')

    def retrieve(self, request, *args, **kwargs):
        user = self.request.user
        instance = UserModel.objects.get(id=user.id)
        base_list = []
        for k, v in enumerate(["普通用户", "正式会员", "服务商", "金牌服务商"]):
            i = k + 1
            if instance.level.level >= i:
                base_list.append({"level_desc": v, "num": instance.leader_set.filter(level__level=i).count()})
        return Response(base_list)


# 绑定上级
class LeaderViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):
    """
    绑定上级
    """
    # serializer_class = BandLeaderSerializers
    authentication_classes = (SessionAuthentication, JSONWebTokenAuthentication)
    permission_classes = (IsAuthenticated,)

    def get_serializer_class(self):
        if self.action == "retrieve":
            return LeaderSerializers
        else:
            return BandLeaderSerializers

    def get_queryset(self):
        if self.action == "retrieve":
            return UserModel.objects.exclude(is_superuser=True)
        else:
            return UserModel.objects.filter(id=self.request.user.id).exclude(is_superuser=True)

    def perform_update(self, serializer):
        return serializer.save()

    @throttle_classes([TransferRateThrottle])
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        updated_instance = self.perform_update(serializer)
        leader = updated_instance.leader
        leader_serializer = UfSerializers(leader, many=False, context=self.get_serializer_context())

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}
        return Response(leader_serializer.data)


# 更新姓名
class NameViewSet(mixins.UpdateModelMixin, viewsets.GenericViewSet):
    """
    绑定上级
    """
    serializer_class = NameSerializers
    authentication_classes = (SessionAuthentication, JSONWebTokenAuthentication)
    permission_classes = (IsAuthenticated, IsOwner)

    def get_queryset(self):
        return UserModel.objects.filter(id=self.request.user.id)


# 绑定银行卡
class BankCardNoViewSet(mixins.UpdateModelMixin, viewsets.GenericViewSet):
    """
    绑定更换银行卡
    """

    authentication_classes = (SessionAuthentication, JSONWebTokenAuthentication)
    permission_classes = (IsOwner, IsAuthenticated)

    def get_serializer_class(self):
        if self.request and self.request.user.bank_card_no:
            return BankCardNoSerializers
        else:
            return BaseBankCardNoSerializers

    def get_queryset(self):
        return UserModel.objects.filter(id=self.request.user.id)


# 更换手机号
class UpdateTelViewSet(mixins.UpdateModelMixin, viewsets.GenericViewSet):
    """
    更换手机号
    """
    serializer_class = TelSerializers
    authentication_classes = (SessionAuthentication, JSONWebTokenAuthentication)
    permission_classes = (IsOwner, IsAuthenticated)

    def get_queryset(self):
        return UserModel.objects.filter(id=self.request.user.id)

        # def update(self, request, *args, **kwargs):
        #     partial = kwargs.pop('partial', False)
        #     instance = self.get_object()
        #     serializer = self.get_serializer(instance, data=request.data, partial=partial)
        #     serializer.is_valid(raise_exception=True)
        #     self.perform_update(serializer)
        #
        #     if getattr(instance, '_prefetched_objects_cache', None):
        #         # If 'prefetch_related' has been applied to a queryset, we need to
        #         # forcibly invalidate the prefetch cache on the instance.
        #         instance._prefetched_objects_cache = {}
        #
        #     user = serializer.object.get('user') or request.user
        #     token = serializer.object.get('token')
        #     response_data = jwt_response_payload_handler(token, user, request)
        #     response = Response(response_data)
        #     if api_settings.JWT_AUTH_COOKIE:
        #         expiration = (datetime.utcnow() +
        #                       api_settings.JWT_EXPIRATION_DELTA)
        #         response.set_cookie(api_settings.JWT_AUTH_COOKIE,
        #                             token,
        #                             expires=expiration,
        #                             httponly=True)
        #     return response


# 个人信息
class SelfInfoViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    个人信息：
        retrieve:查询个人信息
        update:更新个人信息
    """
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    permission_classes = (IsOwner, IsAuthenticated)
    serializer_class = MyInfoSerializer

    def get_queryset(self):
        return UserModel.objects.filter(id=self.request.user.id)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        response_data = serializer.data
        if instance.show_qr_code:
            instance.show_qr_code = False
            instance.save()
        if instance.public_account and instance.public_account.sign != "youpinhuiyuan":
            instance.show_public_account = False
            instance.save()
        return Response(response_data)


# 优秀服务商
class UfViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    优秀服务商
        list: 列表
    """
    serializer_class = UfSerializers
    queryset = UserModel.objects.filter(flag=True)


# 会员升级进度
class LevelUpProgress(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsOwner, IsAuthenticated)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    queryset = LevelDesc.objects.all()

    def retrieve(self, request, *args, **kwargs):
        user = request.user
        if user.level.leader:
            leader_level = user.level.leader
            leader_level_num = leader_level.num
            leader_level_cash_num = leader_level.cash_num
            num = leader_level_num - user.lower_num
            cash_num = (leader_level_cash_num - user.user_perf) / 100.0
            title = "升级为%s？" % leader_level.get_level_display()
            msg = "您和您团队累计再消费{cash_num}元".format(num=num, cash_num=cash_num)
        else:
            msg = "恭喜您成为金牌服务商！"
            title = "金牌服务商"
        return Response(OrderedDict([("result", msg), ("title", title)]))


# 菜单权限
class MenusViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsOwner, IsAuthenticated)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = MenusSerializers

    def get_queryset(self):
        user = self.request.user
        return Menus.objects.filter(company=user.company, parents__isnull=True)


# 后台用户登录
class ObtainJSONWebToken(JSONWebTokenAPIView):
    """
    API View that receives a POST with a user's username and password.

    Returns a JSON Web Token that can be used for authenticated requests.
    """
    serializer_class = AdminLoginSerializers

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            if user and token:
                response_data = jwt_response_payload_handler(token, user, request)
                coffee_channel = user.coffee_channel
                response_data["user_role"] = 0 if user.username == "admin" else user.coffee_channel.channel_type
                response_data["channel_id"] = coffee_channel.id if coffee_channel else ""
                response_data["user_id"] = user.id
                response_data["username"] = user.username
                response_data["channel_name"] = coffee_channel.name if coffee_channel else ""
                response_data["channel_img"] = coffee_channel.img if coffee_channel else ""
                response = Response(response_data)
                if api_settings.JWT_AUTH_COOKIE:
                    expiration = (datetime.datetime.utcnow() +
                                  api_settings.JWT_EXPIRATION_DELTA)
                    response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                        token,
                                        expires=expiration,
                                        httponly=True)
                print(response_data)
                return response
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 微信注册登录
class WXLoginRegisterViewSet(JSONWebTokenAPIView):
    serializer_class = WXLoginSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            if user and token:
                response_data = jwt_response_payload_handler(token, user, request)
                response = Response(response_data)
                if api_settings.JWT_AUTH_COOKIE:
                    expiration = (datetime.datetime.utcnow() +
                                  api_settings.JWT_EXPIRATION_DELTA)
                    response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                        token,
                                        expires=expiration,
                                        httponly=True)
                print(response_data)
                return response
            else:
                openid_e = serializer.object.get("openid_e")
                print("openid_e", openid_e)
                return Response({"openid_e": openid_e})

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 根据id获取用户昵称
class NickNameViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    serializer_class = NickNameSerializers
    queryset = UserModel.objects.all()


# 我的推广图
class PopularsViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    authentication_classes = (SessionAuthentication, JSONWebTokenAuthentication)
    permission_classes = (IsAuthenticated, IsOwner)
    serializer_class = PopularSerializers

    def get_queryset(self):
        user = self.request.user
        return user.popular_user_set.all()

    def list(self, request, *args, **kwargs):
        self.make_popular()
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def make_popular(self):
        today = datetime.date.today()
        queryset = BasePopularImg.objects.all()  # 拿到要做推广图的背景图片
        user_qr_code_queryset = self.get_queryset()  # 拿到之前已经做好的推广图
        qr_code_buf = None
        user = self.request.user
        czb_api = get_czb_api("youpinhuiyuan")
        content = get_czb_channel_auth(user, czb_api)
        if content:
            return Response(content)

        for i in queryset:  # 遍历推广图原来的背景图
            if i.ordering == 1:
                if self.request.query_params.get("position"):
                    from apps.czb.filters import GasStationInfoFilter
                    from apps.czb.views import QueryPriceByPhone
                    background_path = os.path.join(MEDIA_ROOT, i.img.path)

                    queryset_result = QueryPriceByPhone.queryset
                    value = self.request.query_params.get("position")
                    queryset_result = queryset_result.exclude(gasName__contains="车主邦")
                    queryset_result = GasStationInfoFilter().filter_position(queryset_result, "position", value)
                    queryset_result = GasStationInfoFilter().filter_oil_No(queryset_result, "oil_No", 92)

                    queryset_gasIds = queryset_result[0:99].values("gasId")
                    gas_ids = ",".join((i.get("gasId") for i in queryset_gasIds))
                    response = czb_api.query_price_by_phone(gas_ids, self.request.user.mobile)
                    result = response.get("result")
                    if not result:
                        result = []
                    gas_json_list = in_time_update_oil(result, 92)
                    gas_info_list_sort = distance_sorted(gas_json_list, value)
                    gas_info_list_sort = gas_info_list_sort[:3]
                    # queryset_result = queryset_result.filter(
                    #     gasId__in=[gasInfo.get("gasId") for gasInfo in gas_info_list_sort])
                    finance_c2c_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
                    font_file = os.path.join(finance_c2c_dir, "core/font_file/msyh.ttc").replace("\\", "/")
                    int_time = int(time.time())
                    text = Config.czb_client.format(user_id=user.id)
                    qr_code_stream, qr_code_buf = EditPicture.make_qr_code(text)
                    # 获取buf
                    base_img_file, base_img_buf = EditPicture.open_rb_to_img(background_path)
                    # 转换尺寸
                    qr_code_buf_resize, qr_code_buf_resize_buf = EditPicture.resize_img_by_bytes(qr_code_buf,
                                                                                                 box=(217, 217))
                    # 贴图
                    buf, bottom_img = EditPicture.past_img_by_bytes(base_img_buf, qr_code_buf_resize_buf,
                                                                    box=(254, 977))
                    # 写文字
                    # {font_file: "绝对路径", font_size: 字号, box: (x, y), words: "文字", "color": (0, 0, 0)}
                    line = 0
                    lines = []
                    for gas in gas_info_list_sort:
                        priceYfq = gas.get("priceYfq")
                        gasName = gas.get("gasName")
                        priceOfficial = gas.get("priceOfficial")
                        dif_price = "%.2f" % (float(priceOfficial) - float(priceYfq))
                        if float(dif_price) > 0:
                            if line == 0:
                                data1 = dict()
                                data1["font_file"] = font_file
                                data1["font_size"] = 28
                                data1["box"] = (81, 662)
                                data1["words"] = gasName
                                data1["color"] = (0, 0, 0)
                                data2 = dict()
                                data2["font_file"] = font_file
                                data2["font_size"] = 34
                                data2["box"] = (447, 662)
                                data2["words"] = "￥%s" % priceYfq
                                data2["color"] = (226, 34, 28)
                                data3 = dict()
                                data3["font_file"] = font_file
                                data3["font_size"] = 19
                                data3["box"] = (568, 669)
                                data3["words"] = "已降%s元" % dif_price
                                data3["color"] = (226, 34, 28)
                                lines.append(data1)
                                lines.append(data2)
                                lines.append(data3)
                            if line == 1:
                                data1 = dict()
                                data1["font_file"] = font_file
                                data1["font_size"] = 28
                                data1["box"] = (81, 760)
                                data1["words"] = gasName
                                data1["color"] = (0, 0, 0)
                                data2 = dict()
                                data2["font_file"] = font_file
                                data2["font_size"] = 34
                                data2["box"] = (447, 760)
                                data2["words"] = "￥%s" % priceYfq
                                data2["color"] = (226, 34, 28)
                                data3 = dict()
                                data3["font_file"] = font_file
                                data3["font_size"] = 19
                                data3["box"] = (568, 767)
                                data3["words"] = "已降%s元" % dif_price
                                data3["color"] = (226, 34, 28)
                                lines.append(data1)
                                lines.append(data2)
                                lines.append(data3)
                            if line == 2:
                                data1 = dict()
                                data1["font_file"] = font_file
                                data1["font_size"] = 28
                                data1["box"] = (81, 861)
                                data1["words"] = gasName
                                data1["color"] = (0, 0, 0)
                                data2 = dict()
                                data2["font_file"] = font_file
                                data2["font_size"] = 34
                                data2["box"] = (447, 861)
                                data2["words"] = "￥%s" % priceYfq
                                data2["color"] = (226, 34, 28)
                                data3 = dict()
                                data3["font_file"] = font_file
                                data3["font_size"] = 19
                                data3["box"] = (568, 868)
                                data3["words"] = "已降%s元" % dif_price
                                data3["color"] = (226, 34, 28)
                                lines.append(data1)
                                lines.append(data2)
                                lines.append(data3)
                            line += 1
                    bottom_word = "%s月%s日优惠价（扫码了解更多）" % (today.month, today.day)
                    # bottom_word = "页面价格为%s加油优惠价格(更多优惠扫码了解)" % datetime.datetime.now().strftime("%m-%d")
                    lines.append({"font_file": font_file, "font_size": 20, "box": (238, 1296),
                                  "words": bottom_word, "color": (52, 52, 52)})
                    im, buf = EditPicture.write_words_return(bottom_img, lines)

                    popular_url = "https://shop.kalaibao.com/{0}/popular/{1}-{2}.jpg?s={3}".format(
                        Config.shop_oss_base_path, user.id,
                        10, int_time)
                    # 上传oss
                    EditPicture.oss_upload_bytes(buf, 'http://oss-cn-beijing.aliyuncs.com', "zaoqi",
                                                 "{0}/popular/{1}-{2}.jpg".format(
                                                     Config.shop_oss_base_path, user.id, 10))
                    # 建立关系， 建立之前先删除
                    PopularQrCode.objects.filter(img__ordering=2).delete()
                    instance, created = PopularQrCode.objects.get_or_create(
                        user=user,
                        img=i
                    )
                    instance.url = popular_url
                    instance.create_date = datetime.date.today()
                    instance.save()
                else:
                    pass
            elif i.ordering == 2:
                if self.request.query_params.get("position"):
                    pass
                else:
                    if user_qr_code_queryset.filter(img_id=i.id).exists() or user_qr_code_queryset.filter(
                            img__ordering=1, create_date=datetime.date.today()).exists():
                        # 如果无数据的图存在了 或者 有数据的今天的图存在了就pass
                        pass
                    else:
                        background_path = os.path.join(MEDIA_ROOT, i.img.path)
                        finance_c2c_dir = os.path.dirname(
                            os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
                        font_file = os.path.join(finance_c2c_dir, "core/font_file/msyh.ttc").replace("\\", "/")
                        int_time = int(time.time())
                        text = Config.czb_client.format(user_id=user.id)
                        qr_code_stream, qr_code_buf = EditPicture.make_qr_code(text)
                        # 获取buf
                        base_img_file, base_img_buf = EditPicture.open_rb_to_img(background_path)
                        # 转换尺寸
                        qr_code_buf_resize, qr_code_buf_resize_buf = EditPicture.resize_img_by_bytes(qr_code_buf,
                                                                                                     box=(217, 217))
                        # 贴图
                        buf, bottom_img = EditPicture.past_img_by_bytes(base_img_buf, qr_code_buf_resize_buf,
                                                                        box=(254, 977))
                        popular_url = "https://shop.kalaibao.com/{0}/popular/{1}-{2}.jpg?s={3}".format(
                            Config.shop_oss_base_path, user.id,
                            i.id, int_time)
                        # 上传oss
                        EditPicture.oss_upload_bytes(buf, 'http://oss-cn-beijing.aliyuncs.com', "zaoqi",
                                                     "{0}/popular/{1}-{2}.jpg".format(
                                                         Config.shop_oss_base_path, user.id, i.id))
                        # 建立关系,建立之前先删除
                        PopularQrCode.objects.filter(img__ordering=1, user=user).delete()
                        PopularQrCode.objects.create(
                            user=user,
                            url=popular_url,
                            img=i
                        )

            elif user_qr_code_queryset.filter(img_id=i.id).exists():
                # 如果已经生成了推广图 就不再生成
                pass
            else:
                # else 就去生成
                if not qr_code_buf:
                    # 如果没有二维码上传二维码到oss上
                    text = Config.client.format(user_id=user.id)
                    qr_code_stream, qr_code_buf = EditPicture.make_qr_code(text)
                # 找到背景图
                background_path = os.path.join(MEDIA_ROOT, i.img.path)
                # 获取buf
                base_img_file, base_img_buf = EditPicture.open_rb_to_img(background_path)
                # 转换尺寸
                qr_code_buf_resize, qr_code_buf_resize_buf = EditPicture.resize_img_by_bytes(qr_code_buf,
                                                                                             box=eval(
                                                                                                 i.qr_code_size))
                # 贴图
                buf, bottom_img = EditPicture.past_img_by_bytes(base_img_buf, qr_code_buf_resize_buf,
                                                                box=eval(i.qr_position))
                popular_url = "https://shop.kalaibao.com/{0}/popular/{1}-{2}.jpg".format(
                    Config.shop_oss_base_path, user.id, i.id)
                # 上传oss
                EditPicture.oss_upload_bytes(buf, 'http://oss-cn-beijing.aliyuncs.com', "zaoqi",
                                             "{0}/popular/{1}-{2}.jpg".format(
                                                 Config.shop_oss_base_path, user.id, i.id))
                # 建立关系
                PopularQrCode.objects.create(
                    user=user,
                    url=popular_url,
                    img=i
                )


# 通联个人中心
class TLMyCenter(APIView):
    authentication_classes = (SessionAuthentication, JSONWebTokenAuthentication)
    permission_classes = (IsAuthenticated, IsOwner)

    def get(self, request):
        user = request.user
        merchant_user_id = user.id
        h5_client = get_TLClient()
        if hasattr(user, "userprofileextend"):
            userId = user.userprofileextend.userId
            if userId:
                token = user.userprofileextend.get_tl_user_token(h5_client)
                # url = h5_client.h5_my_center_api(user.mobile, token, userId)
                url = h5_client.h5_my_center_api(user.id, token, userId)
                content = {"url": url}
                return Response(content)
            else:
                user_extend = user.userprofileextend
                token = user_extend.get_tl_user_token(h5_client)
                # url = h5_client.h5_my_center_api(user.mobile, token, user_extend.userId)
                url = h5_client.h5_my_center_api(user.id, token, user_extend.userId)
                content = {"url": url}
                return Response(content)
        else:
            user_extend = UserProfileExtend.objects.create(
                user_id=user.id
            )
            token = user_extend.get_tl_user_token(h5_client)
            # url = h5_client.h5_my_center_api(user.mobile, token, user_extend.userId)
            url = h5_client.h5_my_center_api(user.id, token, user_extend.userId)
            content = {"url": url}
            return Response(content)
